module.exports = (app) => {
  const express = require("express");
  const jwt = require("jsonwebtoken");
  const assert = require("http-assert");
  const AdminUser = require("../../models/AdminUser");
  const router = express.Router({
    mergeParams: true,
    //让子路由继承父路由的参数
  }); //express的一个子路由
  //const  req.Model = require("../../models/ req.Model");
  //路由接口

  //新建分类
  router.post("/", async (req, res) => {
    const model = await req.Model.create(req.body);
    // console.log(req.body)
    res.send(model);
  });
  //编辑分类
  router.put("/:id", async (req, res) => {
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body);
    //通过id寻找，找完后就更新
    //console.log(req.body)
    res.send(model);
  });
  //删除分类
  router.delete("/:id", async (req, res) => {
    await req.Model.findByIdAndDelete(req.params.id, req.body);
    // console.log(req.body)
    res.send({
      success: true,
    });
  });
  //查找分类(分类列表)

  router.get("/", async (req, res) => {
    const queryOptions = {};
    if (req.Model.modelName == "Category") {
      queryOptions.populate = "parent";
    }
    //通用性，扩展性
    const items = await req.Model.find().setOptions(queryOptions);
    //console.log(req.body)
    res.send(items);
  });
  //查找id
  router.get("/:id", async (req, res) => {
    const model = await req.Model.findById(req.params.id);
    //console.log(req.body)
    res.send(model);
  });

  /**
   * 路由挂载
   */
  //登录校验中间件
  const authMiddleware = require("../../middleware/auth");
  const resourceMiddleware = require("../../middleware/resource");
  app.use(
    "/admin/api/rest/:resource",
    authMiddleware(),
    resourceMiddleware(),
    router
  );

  /**
   * 自定义接口
   */

  //carEdit页面查询所需要显示的分类
  const Category = require("../../models/Category");
  //查找品牌
  app.get("/admin/api/category/brand", async (req, res) => {
    const { _id } = await Category.findOne({ name: "品牌" });
    const model = await Category.find({ parent: _id });
    //console.log(model);
    res.send(model);
  });
  //查找车型
  app.get("/admin/api/category/carModel", async (req, res) => {
    const { _id } = await Category.findOne({ name: "车型" });
    const model = await Category.find({ parent: _id });
    //console.log(model);
    res.send(model);
  });
  //查找颜色
  app.get("/admin/api/category/color", async (req, res) => {
    const { _id } = await Category.findOne({ name: "颜色" });
    const model = await Category.find({ parent: _id });
    //console.log(model);
    res.send(model);
  });

  //查找燃油类型
  app.get("/admin/api/category/fuelType", async (req, res) => {
    const { _id } = await Category.findOne({ name: "燃料类型" });
    const model = await Category.find({ parent: _id });
    // console.log(model);
    res.send(model);
  });

  //可以接收上传文件的接口
  const multer = require("multer");
  const upload = multer({ dest: __dirname + "/../../uploads" });
  //"上传中间件" 执行multer，写出上传地址
  app.post("/admin/api/upload", upload.single("file"), async (req, res) => {
    const file = req.file;
    //本身是没有req.file因为增加了中间件multer，因此多了这个属性
    file.url = `http://localhost:3001/uploads/${file.filename}`;
    res.send(file);
    //需要一个中间件来处理专门用于上传数据的，multer
    //singel表示单个文件的上传
  });

  app.post("/admin/api/login", async (req, res) => {
    const { username, password } = req.body;
    const user = await AdminUser.findOne({ username }).select("+password");
    assert(user, 422, "用户不存在");
    const isValid = require("bcrypt").compareSync(password, user.password);
    assert(isValid, 422, "密码错误");
    const token = jwt.sign({ id: user._id }, app.get("secret"));
    res.send({ user: user, token });
  });

  app.post("/admin/api/register", async (req, res) => {
    const { username, password } = req.body;
    const user = await AdminUser.findOne({ username }).select("+password");
    if (user) {
      res.status(422).send({ message: "用户已存在" });
    } else {
      const model = await AdminUser.create({ username, password});
      const token = jwt.sign({ id: model._id }, app.get("secret"));
      res.send({ token, username, uid: model._id });
    }
  });

  //错误处理函数
  app.use(async (err, req, res, next) => {
    res.status(err.statusCode || 500).send({
      message: err.message,
    });
  });
}; //导出一个函数app
